<%@ page contentType="text/html; charset=UTF-8"%>
<%@page pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<html>
<head>
<title>南京移动地图信息系统</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="shortcut icon" href="<%=basePath%>images/favicon.ico">
<script src="<%=basePath%>jquery-easyui-1.2.6/jquery-1.7.2.min.js"
	type="text/javascript"></script>
<script src="<%=basePath%>jquery-easyui-1.2.6/jquery.easyui.min.js"
	type="text/javascript"></script>
<script src="<%=basePath%>js/jquery.toast.js"
			type="text/javascript"></script>
<script type="text/javascript" src="<%=basePath%>jquery-easyui-1.2.6/locale/easyui-lang-zh_CN.js"></script>
<link href="<%=basePath%>jquery-easyui-1.2.6/themes/default/easyui.css"
	rel="stylesheet" type="text/css" />
<link href="<%=basePath%>jquery-easyui-1.2.6/themes/icon.css" rel="stylesheet"
	type="text/css" />
<script type="text/javascript" src="<%=basePath%>jquery/jquery.autocomplete.js"></script>
<script type="text/javascript" src="<%=basePath%>js/markerclusterer.js"></script>
<script type="text/javascript" src="<%=basePath%>js/json2.js"></script>
<link rel="Stylesheet" href="<%=basePath%>jquery/jquery.autocomplete.css" />
	<style>
	    body{margin:0;padding:0;background:#ffffff;overflow-y:hidden;font:13px Verdana,Tahoma,Arial,sans-serif;line-height:1.6em;}
		a:link { text-decoration: none;color: blue}
		a:visited {color: blue}  
		a:hover {color: blue}    
		a:active {color: blue} 
        .toast{
		/* border properties */
		border-radius: 4px;
		-moz-border-radius: 4px;
		-webkit-border-radius: 4px;
		border: 2px solid #CCCCCC;
 
		/* Aesthetics */
		position: absolute;
		padding: 10px;
		color: #ffffff;
		background-color:rgba(0,0,0, 0.8);
		display:none;}
		#passwordfm{  
            margin:0;  
            padding:10px 30px;  
        }  
        .ftitle{  
            font-size:14px;  
            font-weight:bold;  
            color:#666;  
            padding:5px 0;  
            margin-bottom:10px;  
            border-bottom:1px solid #ccc;  
        }  
        .fitem{  
            margin-bottom:5px;  
        }  
        .fitem label{  
            display:inline-block;  
            width:80px;  
        } 
	</style>
<head>
<script type="text/javascript">
	var path = '<%=path%>';
</script>
<script src="<c:url value="/js/mapapi.js"/>"
	type="text/javascript"></script>
<script type="text/javascript">
	function deleteCarType(id) {
		$.ajax({
			type : 'post',
			url : 'test.action',
			data : 'carTypeId=' + id,
			async : true,
			success : function(data) {
				//alert("success");

			},
			error : function(data) {
				alert(data);
			}
		});
	};

	function getRegionTreeCheckItems(newworkTypes){
		$.ajax({
			type : 'post',
			url : 'getRegionTreeCheckItems.action',
			data : 'data=' + $("#combox_zone").combobox('getText')+':'+newworkTypes,
			async : true,
			success : function(data) {
				showNetWorkMap(data);
			},
			error : function(data) {
				$.toast({
					message: "操作失败!!",
					displayTime: 1000
				});
			}
		});
	}
	
	function getGridTreeCheckItems(newworkTypes){
		$.ajax({
			type : 'post',
			url : 'getGridTreeCheckItems.action',
			data : 'data=' + $("#combox_zone").combobox('getText')+':'+newworkTypes,
			async : true,
			success : function(data) {
				showNetWorkMap(data);
			},
			error : function(data) {
				$.toast({
					message: "操作失败！!",
					displayTime: 1000
				});
			}
		});
	}
	
	function getMicroRegionTreeCheckItems(newworkTypes){
		$.ajax({
			type : 'post',
			url : 'getMicroRegionTreeCheckItems.action',
			data : 'data=' + $("#combox_zone").combobox('getText')+':'+newworkTypes,
			async : true,
			success : function(data) {
				showNetWorkMap(data);
			},
			error : function(data) {
				$.toast({
					message: "操作失败！!",
					displayTime: 1000
				});
			}
		});
	}
	var map;
	var regionId = 1;
	var titlemap_url = '<c:url context="/gmapapi" value="/tilemap/"></c:url>';
	var pic_url = '<c:url context="/pic" value="/"></c:url>';
	var markersArray = [];
	var polygonArray = [];
	var infoWindow = new google.maps.InfoWindow;
	var regionName = null;
	var markerCluster = null;
	var mapCenterOptions = [{'id': 1,'zoom': 10,'longitude': 32.059,'latitude':118.840},{'id' :2,'zoom': 12,'longitude': 32.0593,'latitude':118.840},{'id':3,'zoom': 12,'longitude': 31.9734,'latitude':118.752},{'id' :4,'zoom': 12,'longitude': 32.0177,'latitude':118.728},{'id':5,'zoom': 11,'longitude': 32.133,'latitude':118.952},{'id':6,'zoom': 10,'longitude': 31.909,'latitude':118.899},{'id': 7,'zoom': 10,'longitude': 32.072,'latitude':118.577},{'id' :8,'zoom': 10,'longitude': 32.411,'latitude':118.791},{'id': 9,'zoom': 10,'longitude': 31.629,'latitude': 119.059},{'id' :10,'zoom': 10,'longitude': 31.350,'latitude':118.967}];
	var dataGridJson = null;
	var pageCount = 10;
	var pageNum = 1;
	var latlon;
	var poygon;
	
	function CoordMapType(tileSize) {
	    this.tileSize = tileSize;
	  }
	CoordMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
		var div = ownerDocument.createElement('DIV');
		var ymax = 1 << zoom;
		var y = ymax - coord.y - 1;
		zoom = zoom + 1;
		div.innerHTML = "x = " + coord.x + ", y = " + coord.y + ", zoom = "
				+ zoom;
		div.style.width = this.tileSize.width + 'px';
		div.style.height = this.tileSize.height + 'px';
		div.style.fontSize = '10';
		div.style.borderStyle = 'solid';
		div.style.borderWidth = '1px';
		div.style.borderColor = '#FF0000';
		return div;
	}
	function LocalMapType() {
	}

	LocalMapType.prototype.tileSize = new google.maps.Size(256, 256);
	LocalMapType.prototype.maxZoom = 17;
	LocalMapType.prototype.minZoom = 10;
	LocalMapType.prototype.name = "\u672C\u5730";

	LocalMapType.prototype.isPng = true;

	LocalMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
		var img = ownerDocument.createElement("img");
		img.style.width = this.tileSize.width + "px";
		img.style.height = this.tileSize.height + "px";
		var ymax = 1 << zoom;
		zoom = zoom + 1;
		var strURL = titlemap_url + zoom + "/" + coord.y + "/" + coord.x;
		img.src = strURL;
		return img;
	};

	var localMapType = new LocalMapType();

	function initMap() {
		var latlng = new google.maps.LatLng(32.117475, 118.797455);
		var myOptions = {
			backgroundColor : '#FFFFFF',
			zoom : 12,
			center : latlng,
			mapTypeControl : false,
			mapTypeControlOptions : {
				mapTypeIds : [ "local", google.maps.MapTypeId.ROADMAP ]
			},
			panControl : true,
			zoomControl : true,
			streetViewControl : false
		};
		map = new google.maps.Map($("#map_canvas").get(0), myOptions);
		map.mapTypes.set('local', localMapType);
		map.setMapTypeId('local');
	}
	
	function qq(value, name) {
		alert(value + ":" + name);
	}

	var websites = [ "Google", "NetEase", "Sohu", "Sina", "Sogou", "中国",
			"Tencent", "Taobao", "Tom", "Yahoo", "JavaEye", "华锋", "Alipay" ];
	function reloadTree(treeid) {
		//alert(treeid);
		$("#tree_microRegion").tree({
			url : 'getMicroRegionTreeJson.action?id=' + treeid
		});
		$("#tree_region").tree({
			url : 'getRegionTreeJson.action?id=' + treeid
		});
		
		$("#tree_grid").tree({
			url : 'getGridTreeJson.action?id=' + treeid
		});
	}
	function clearMap() {
		if (markersArray) {
			for (i in markersArray) {
				markersArray[i].setMap(null);
			}
			markersArray.length = 0;
		}
		
		if(markerCluster != null){
			markerCluster.clearMarkers();
		}
	}
	function clearPolygons(){
		if (polygonArray) {
			for (j in polygonArray) {
				polygonArray[j].setMap(null);
			}
			polygonArray.length = 0;
		}
	}
	
	function generateDataGridJson(){
		if(dataGridJson  ==  null){
			return ;
		}
		var count = dataGridJson.length;
		if(count < this.pageSize){
			return dataGridJson;
		}else{
			var json = '[';
			for(var i = this.pageCount*(this.pageNum-1);i<count && i< this.pageCount*this.pageNum;i++){
				
				json+=JSON.stringify(dataGridJson[i])+',';
			}
			json = json.substring(0,json.length-1);
			json += ']';
			var json1 = {'total':dataGridJson.length,'rows':eval(json)};
			return json1;
		}
	}
	
	function showNetWorkMap(channelnetworks) {
		clearMap() ;
		dataGridJson = channelnetworks;
		//var json = {'total':dataGridJson.length,'rows':generateDataGridJson()};
		$("#data_grid").datagrid("options").pageNumber = 1;
		$("#data_grid").datagrid('getPager').pagination({pageNumber:1,pageSize:10});
		pageCount = 10;
		pageNum = 1;
		$("#data_grid").datagrid('reload');
		$('#data_grid').datagrid('loadData', generateDataGridJson());
		if(channelnetworks != null){
			for(var i=0; i<channelnetworks.length; i++){
			    var marker = new google.maps.Marker({
					//map : map,
					position : new google.maps.LatLng(channelnetworks[i].latitude, channelnetworks[i].longitude),
					title : channelnetworks[i].name,
					icon : "<c:url value="/images/"/>" + channelnetworks[i].networkType + ".png"
				});			
				bindInfoWindow(marker, channelnetworks[i]);
				markersArray.push(marker);
			  }
			markerCluster = new MarkerClusterer(map, markersArray,{maxZoom: 16});
		}
	}
	function bindInfoWindow(marker, channelNetwork) {
		google.maps.event.addListener(marker, 'click', function() {
			openInfoWindow(marker, channelNetwork);
		});
	}
	function openInfoWindow(marker, channelNetwork) {	
		infoWindow.setContent(getInfoWindowContent(channelNetwork));
		infoWindow.open(map, marker);	
	}
	function getInfoWindowContent(channelNetwork) {
		var picStr = "";
		if(channelNetwork.pic_Url != ""){
			picStr = '<img src='+pic_url+channelNetwork.pic_Url+' width="200px" heigth="200px" />';
		}
		return '<div id="info" style="line-height:20px">' + 
		"网点区域:"+channelNetwork.regionName+"<br/>"+
		"渠道代码:"+channelNetwork.channelCode+"<br/>"+
		"营销单元:"+channelNetwork.maketingUnit+"<br/>"+
		"微区域:"+channelNetwork.microRegion+"<br/>"+
		"营业厅/渠道:"+channelNetwork.channelType+"<br/>"+
		"网点类型:"+channelNetwork.networkType+"<br/>"+
		"网点名称:"+channelNetwork.name+"<br/>"+
		"外包情况:"+channelNetwork.outsourcing+"<br/>"+
		"地址:"+channelNetwork.address+"<br/>"+
		"店长/渠道经理:"+channelNetwork.manager+"<br/>"+
		"网点经度:"+channelNetwork.longitude+"<br/>"+
		"网点纬度:"+channelNetwork.latitude+"<br/>"+
		"联系电话:"+channelNetwork.phone+"<br/>"+
		"网点性质:"+channelNetwork.specialty+"<br/>"+
		"区域环境:"+(channelNetwork.regionEnvironment != null ?channelNetwork.regionEnvironment :'') +"<br/>"+
		'</div>'+picStr
	}
	
	function regionTreeCheckEvent(){
		clearPolygons();
		var nodes = $('#tree_region').tree('getChecked');
		var s = '';  
        for(var i=0; i<nodes.length; i++){  
            if (s != '') s += ',';  
            if (nodes[i].id != 0){
            	 s += nodes[i].id;  
            }
        }
        if(s != ''){
        	getRegionTreeCheckItems(s);
        }else{
        	clearMap();
        	$('#data_grid').datagrid('loadData',[]);
        }
	}
	
	function gridTreeCheckEvent(){
		clearPolygons();
		var nodes = $('#tree_grid').tree('getChecked');
		var s = '';  
        for(var i=0; i<nodes.length; i++){  
        	if (s != '') s += ',';  
            if (nodes[i].attributes+"" != "undefined"){
            	 s += nodes[i].attributes;  
            }
        }
        if(s != ''){
        	getGridTreeCheckItems(s);
        	getGridPathLatLng(s);
        }else{
        	clearMap();
        	$('#data_grid').datagrid('loadData',[]);
        }
	}
	
	function microRegionTreeCheckEvent(){
		var nodes = $('#tree_microRegion').tree('getChecked');
		var s = '';  
        for(var i=0; i<nodes.length; i++){  
        	if (s != '') s += ',';  
            if (nodes[i].attributes+"" != "undefined"){
            	 s += nodes[i].attributes;  
            }
        }
        if(s != ''){
        	getMicroRegionTreeCheckItems(s);
        	getRegionPathLatLng(s)
        }else{
        	$('#data_grid').datagrid('loadData',[]);
        	clearMap();
        	clearPolygons();
        }
	}
	
	function getGridPathLatLng(s){
		$.ajax({
			type : 'post',
			url : 'getGridPathLatLng.action',
			data : 'data=' + s,
			async : true,
			success : function(data) {
				showPolygons(data);
			},
			error : function(data) {
				$.toast({
					message: "操作失败！!",
					displayTime: 1000
				});
			}
		});
	}
	
	function getRegionPathLatLng(s){
		$.ajax({
			type : 'post',
			url : 'getRegionPathLatLng.action',
			data : 'data=' + s,
			async : true,
			success : function(data) {
				showPolygons(data);
			},
			error : function(data) {
				$.toast({
					message: "操作失败！!",
					displayTime: 1000
				});
			}
		});
	}
	
	function showPolygons(pathValue){
		clearPolygons();
		for(var i=0; i<pathValue.length; i++){
			var latlonStr = String(pathValue[i]);
			var polygon = new google.maps.Polygon({
					                      strokeColor: "#FF0000",
					                      strokeOpacity: 0.8,
					                      strokeWeight: 2,
					                      fillColor: "#FF0000",
					                      fillOpacity: 0.35
					                    });
			polygon.setMap(map);
			var path = polygon.getPath();
			var latlonArray = latlonStr.split(";");
			for(var j=0; j<latlonArray.length; j++){
				var latlon = latlonArray[j].split(",");
				path.push(new google.maps.LatLng(latlon[0],latlon[1]));
			}
			polygonArray.push(polygon);
		}
	}
	function reloadMapCenter(id){
		if(map != null){
			map.setCenter(new google.maps.LatLng(mapCenterOptions[id].longitude,mapCenterOptions[id].latitude));
			map.setZoom(mapCenterOptions[id].zoom);
		}
		
	}
	function searchByKeyword(){
		if($("#Input_Search").val() == ""){
			$.toast({
				message: "请输入要查询内容!",
				displayTime: 1000
			});
			return;
		}
		$.ajax({
			type : 'post',
			url : 'searchByKeyword.action',
			data : 'keyWord='+$("#Input_Search").val(),
			async : true,
			success : function(data) {
				showNetWorkMap(data);
			},
			error : function(data) {
				$.toast({
					message: "操作失败!",
					displayTime: 1000
				});
			}
		});
	}
	function changePassword(){
		$('#changePassworddlg').dialog('open').dialog('setTitle', '修改密码');
		$('#passwordfm').form('clear');
	}
	function saveNewPassword(){
		if($("#oldPassword").val()=='' ||$("#newPassword").val()==''||$("#newPassword1").val()==''){
			alert('请填写完整信息');
			return;
		}
		if($("input[name='newPassword']").val()!=$("input[name='newPassword1']").val()){
			alert('两次密码不一样！');
			return
		}
		$.ajax({
			type : 'post',
			url : 'changePassword.action',
			data : 'oldPassword='+$("#oldPassword").val()+'&'+'newPassword='+$("#newPassword").val(),
			async : true,
			success : function(data) {
				var kkk = eval('('+data+')');
				if(kkk.result == 3){
					alert('原密码错误');
					return;
				}
				$('#changePassworddlg').dialog('close');
				$.toast({
					message: "修改成功!",
					displayTime: 1000
				});
			},
			error : function(data) {
				alert('操作失败!');
			}
		});
	}
	function reloadMicroRegion(newValue){
		$("#microRegion").combobox({
			url : 'getMicroRegionComboxJson.action?id=' + newValue,
			width:'120'
		});
	}
	
	function resetDrawing(){
		latlon = null;
		if(this.polygon){
			this.polygon.setMap(null);
		}
		polygon = null;
	}
	function startDrawing(){
		 resetDrawing();
		 polygon =  new google.maps.Polygon({
             strokeColor: "#FF0000",
             strokeOpacity: 0.8,
             strokeWeight: 2,
             fillColor: "#FF0000",
             fillOpacity: 0.35
           });
		 polygon.setMap(map);
		 latlon = polygon.getPath();
		 google.maps.event.addListener(map, "click", function(event) {  
			 	latlon.push(event.latLng);
			 }); 
	}
	
	function stopDrawing(){
		google.maps.event.clearListeners(map,"click");
	}
	
	function savePath(){
		if($("#microRegion").combobox('getValue') == ""){
			$.toast({
				message: "请选择微区域!",
				displayTime: 1000
			});
			return;
		}
		if(latlon+"" == "undefined" || latlon == null || (latlon != null && latlon.length == 0)){
			$.toast({
				message: "请画出微区域!",
				displayTime: 1000
			});
			return;
		}
		$.ajax({
			type : 'post',
			url : 'savePath.action',
			data : 'id='+$("#microRegion").combobox('getValue')+'&'+'path='+JSON.stringify(latlon.b),
			async : true,
			success : function(data) {
				$.toast({
					message: "保存成功!",
					displayTime: 1000
				});
				resetDrawing();
			},
			error : function(data) {
				alert('操作失败!');
			}
		});
	}
	$().ready(function() {
		$("#Input_Search").autocomplete(websites);
		$("#combox_zone").combobox({
			url : 'getComboxJson.action',
			onChange : function(newValue, oldValue) {
				reloadTree(newValue);
				reloadMapCenter(newValue-1);
				clearMap();
				clearPolygons();
			}
		});
		$("#combox_zone").combobox('select', 1);
		$("#tab_tree").tabs({onSelect:function(){clearMap(),clearPolygons()}});
		$("#tree_region").tree({onCheck:function(){regionTreeCheckEvent();}});
		$("#tree_microRegion").tree({onCheck:function(){microRegionTreeCheckEvent();}});
		$("#tree_grid").tree({onCheck:function(){gridTreeCheckEvent();}});
		
	$('#data_grid').datagrid({
			onClickRow : function(rowIndex, rowData) {
					openInfoWindow(markersArray[Number(pageCount*(pageNum-1)+rowIndex)],rowData);
			}
		});
	var pg = $("#data_grid").datagrid("getPager");
		if (pg) {
			$(pg).pagination({
				onBeforeRefresh : function() {
				},
				onRefresh : function(pageNumber, pageSize) {
					$('#data_grid').datagrid('loadData', generateDataGridJson());
				},
				onChangePageSize : function() {
				},
				onSelectPage : function(pageNumber, pageSize) {
					pageNum = pageNumber;
					pageCount = pageSize;
					$('#data_grid').datagrid('loadData', generateDataGridJson());
				}
			});
		}
		$("#region").combobox({
			url : 'data/combobox_regiondata.json',
			onChange : function(newValue, oldValue) {
				reloadMicroRegion(newValue);
			}
		});
		//$("#tree_region").tree({url:'getRegionTreeJson.action?id='+regionId});
		//$("#tree_microRegion").tree({url:'getMicroRegionTreeJson.action?id='+regionId});
	});
</script>
<body onload="initMap()" class="easyui-layout">
	<div region="west" split="false" title="菜单" style="width: 350px;">
		<div id="aa" class="easyui-accordion" fit="true">
			<div title="营销区域" selected="true" >
			<div >
				<label>请选择营销区域： </label> <input id="combox_zone"
					style="width: 100px" valueField="id" textField="name"> </input></div>
				<div id='tab_tree' class="easyui-tabs" fit="true">
					<div title="总体" style="padding: 10px;">
						<ul id="tree_region" class="easyui-tree" checkbox="true">
						</ul>
					</div>
					<div title="网格" style="padding: 10px;">
						<ul id="tree_grid" class="easyui-tree" checkbox="true">
						</ul>
					</div>
					<div title="分区域" style="padding-bottom:30px;">
						<ul id="tree_microRegion" class="easyui-tree" checkbox="true" >
						</ul>
					</div>
				</div>
			</div>
			<div title="关键字查询" iconCls="icon-search" style="padding: 10px;">
				<input type="text" id="Input_Search" /> <input type="button"
					id="Btn_Search" value="查询" onclick="searchByKeyword()" />
				<table id="data_grid" title="查询结果" class="easyui-datagrid"
					 idField="itemid" pagination="true" singleSelect="true"
					iconCls="icon-ok">
					<thead>
						<tr>
							<th field="name" align=center width="160"><b>名称</b></th>
							<th field="channelCode" align="center" width="70"><b>代码</b></th>
							<th field="address"  align="center" width="200" ><b>地址</b></th>
						</tr>
					</thead>
				</table>
			</div>
		</div>
	</div>
	</div>
	<div id="map_canvas" split="true" region="center" title="地图"
		style="overflow-x: hidden; overflow-y: hidden;"ackground: #eee;"></div>
	<div id="changePassworddlg" class="easyui-dialog" style="width:380px;height:300px;padding:10px 20px"  
            closed="true" buttons="#changePassworddlg-buttons">  
        <div class="ftitle">修改密码</div>  
        <form id="passwordfm" method="post" novalidate>  
            <div class="fitem">  
                <label>旧密码:</label>  
                <input id="oldPassword" name="oldPassword" class="easyui-validatebox" type="password">  
            </div>  
            <div class="fitem">  
                <label>新密码:</label>  
                <input id="newPassword" name="newPassword" class="easyui-validatebox" type="password">  
            </div>  
            <div class="fitem">  
                <label>重复新密码:</label>
                <input id="newPassword1" name="newPassword1" class="easyui-validatebox" type="password">  
            </div>  
        </form>  
    </div>  
    <div id="changePassworddlg-buttons">  
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveNewPassword()">确定</a>  
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#changePassworddlg').dialog('close')">取消</a>  
    </div>
</body>
</html>
